#include "mem_leak_chk.h"
#include "mem_chk_db.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class CTest{
public:
    CTest() {
        printf("constructor %s:%d\n", __FUNCTION__, __LINE__);
    }
    ~CTest() {
        printf("desstructor %s:%d\n", __FUNCTION__, __LINE__);
    }
    
    void fn() {
        printf("test new-delete class ptr=%p len=%lu\n", this, sizeof(*this));
    }
};

void test_all_ok() {
    char* m = (char*)malloc(64);
    memset(m, 0, 64);
    sprintf(m, "test malloc-free ptr=%p len=%d\n", m, 64);
    printf("%s", m);
    free(m);
    m = 0;
    
    m = (char*)calloc(6, 3);
    printf( "test calloc-free ptr=%p len=%d\n", m, 3 * 6);
    free(m);
    m = 0;
    
    m = (char*)malloc(6);
    printf("test realloc-free ptr=%p len=%d\n", m, 6);
    m = (char*)realloc(m, 14);
    free(m);
    m = 0;
    
    

    int* pi = new int;
    memset(pi, 0, sizeof(int));
    printf("test new-delete basic-type ptr=%p len=%lu\n", pi, sizeof(int));
    delete pi;
    pi = 0;	
    
    m = new char[62];
    memset(m, 0, 62);
    sprintf(m, "test new[]-delete[] ptr=%p len=%d\n", m, 62);
    printf("%s", m);
    delete []m;
    
    CTest* t = new CTest;
    t->fn();
    delete t;
}

void test_memLeak_malloc() {
	char* m = (char*)malloc(32);
	memset(m, 0, 32);
	sprintf(m, "i am test_memLeak_malloc\n");
	printf("%s", m);
	free(m);
	m = 0;
	
	m = (char*)malloc(16);
}

void test_memLeak_calloc() {
	char* m = (char*)calloc(7, 4);
	sprintf(m, "i am test_memLeak_calloc\n");
	printf("%s", m);
}

void test_memLeak_realloc() {
	char* m = (char*)calloc(7, 4);
	m = (char*)realloc(m, 39);
	memset(m, 0, 39);
	sprintf(m, "i am test_memLeak_realloc\n");
	printf("%s", m);
}

void test_memLeak_new_basicType() {
	char* m = new char;
	memset(m, 0, sizeof(char));
	printf("i am %s\n", __FUNCTION__);
}

void test_memLeak_new_array() {
	printf("i am %s\n", __FUNCTION__);
	int* t = new int[7];
}

void test_memLeak_new_class() {
	printf("i am %s\n", __FUNCTION__);
    CTest* t = new CTest;
    //t->fn();
}

int main() {
	test_all_ok();  
	test_memLeak_malloc();
	test_memLeak_calloc();
	test_memLeak_realloc();
	test_memLeak_new_basicType();
	test_memLeak_new_array();
	test_memLeak_new_class();

	print_mem_leak(true);      
    return 0;
}